package com.gnomon.epsos.model;

import java.io.ByteArrayInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.portlet.RenderRequest;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.log4j.Logger;
import org.opensaml.saml2.core.Assertion;

import com.gnomon.LiferayUtils;
import com.gnomon.epsos.service.*;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.model.User;
import com.liferay.util.portlet.PortletProps;

import epsos.ccd.gnomon.xslt.EpsosXSLTransformer;
import epsos.openncp.protocolterminator.ClientConnectorConsumer;
import epsos.openncp.protocolterminator.HCPIAssertionCreator;
import epsos.openncp.protocolterminator.clientconnector.DocumentId;
import epsos.openncp.protocolterminator.clientconnector.EpsosDocument1;
import epsos.openncp.protocolterminator.clientconnector.GenericDocumentCode;
import epsos.openncp.protocolterminator.clientconnector.PatientDemographics;
import epsos.openncp.protocolterminator.clientconnector.PatientId;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean
@SessionScoped
public class MyBean {
	private List<Country> countries;
	private String selectedCountry;
	private List<Identifier> identifiers;
	private List<Demographics> demographics;
	private List<Patient> patients;
	private Patient selectedPatient;
	private List<PatientDocument> patientDocuments;
	private PatientDocument selectedDocument;
	private EpsosDocument selectedEpsosDocument;
	private String documentHtml;
	private List<PatientDocument> patientPrescriptions;
	private String prescriptionHtml;
	private boolean showDemographics;
	private boolean showPatientList = true;
	private StreamedContent prescriptionFile;
	private PatientDocument selectedPrescriptionFile;
	private Assertion hcpAssertion = null;
	private boolean trcAssertionExists = false;
	private boolean trcAssertionNotExists = true;
	private Assertion trcAssertion;
	private String purposeOfUse;
	private String purposeOfUseForPS;
	private String queryPatientsException;
	private String queryDocumentsException;
	private String queryPrescriptionsException;

	private String errorUserAssertion;

	private static Logger log = Logger.getLogger("MyBean");

	public MyBean() {
		countries = new ArrayList<Country>();
		identifiers = new ArrayList<Identifier>();
		demographics = new ArrayList<Demographics>();
		countries = EpsosHelperService.getCountriesFromCS(LiferayUtils
				.getPortalLanguage());
		// showPatientList = false;

		EpsosHelperService.getCountryListNameFromCS(
				LiferayUtils.getPortalLanguage(), countries);
	}

	public void showPrescription(ActionEvent actionEvent)
			throws SystemException {
		RenderRequest renderRequest = (RenderRequest) (FacesContext
				.getCurrentInstance().getExternalContext().getRequestMap()
				.get("javax.portlet.request"));
		String parameter = renderRequest.getParameter("productId");
		log.info("PRODUCT ID: " + parameter);
	}

	public List<Country> getCountries() {
		return countries;
	}

	public String getSelectedCountry() {
		return selectedCountry;
	}

	public void setSelectedCountry(String selectedCountry) {

		// create user assertion
		errorUserAssertion = "";
		Object obj = EpsosHelperService.getUserAssertion();
		System.out.println(obj);
		if (obj instanceof Assertion) {
			hcpAssertion = (Assertion) obj;
		} else if (obj instanceof String) {
			errorUserAssertion = (String) obj;

		}
		User user = LiferayUtils.getPortalUser();
		LiferayUtils.storeToSession("user", user);

		this.selectedCountry = selectedCountry;
		identifiers = new ArrayList<Identifier>();
		Vector vec = EpsosHelperService
				.getCountryIdsFromCS(this.selectedCountry);
		for (int i = 0; i < vec.size(); i++) {
			Identifier id = new Identifier();
			id.setKey(EpsosHelperService.getPortalTranslation(
					((SearchMask) vec.get(i)).getLabel(),
					LiferayUtils.getPortalLanguage())
					+ "*");
			id.setDomain(((SearchMask) vec.get(i)).getDomain());
			if (id.getKey().equals("") || id.getKey().equals("*")) {
				id.setKey(((SearchMask) vec.get(i)).getLabel() + "*");
			}
			identifiers.add(id);
		}

		demographics = new ArrayList<Demographics>();
		vec = EpsosHelperService
				.getCountryDemographicsFromCS(this.selectedCountry);
		for (int i = 0; i < vec.size(); i++) {
			Demographics id = new Demographics();
			if (((Demographics) vec.get(i)).getMandatory())
				id.setLabel(EpsosHelperService.getPortalTranslation(
						((Demographics) vec.get(i)).getLabel(),
						LiferayUtils.getPortalLanguage())
						+ "*");
			else
				id.setLabel(EpsosHelperService.getPortalTranslation(
						((Demographics) vec.get(i)).getLabel(),
						LiferayUtils.getPortalLanguage()));
			id.setLength(((Demographics) vec.get(i)).getLength());
			id.setKey(((Demographics) vec.get(i)).getKey());
			id.setMandatory(((Demographics) vec.get(i)).getMandatory());
			demographics.add(id);
		}
		if (demographics.size() == 0) {
			showDemographics = false;
		} else {
			showDemographics = true;
		}
		LiferayUtils.storeToSession("selectedCountry", selectedCountry);
		patients = new ArrayList<Patient>();
	}

	public void searchPatients() {
		try {
			trcAssertion = null;
			trcAssertionNotExists = true;
			trcAssertionExists = false;
			patients = new ArrayList<Patient>();
			String serviceUrl = PortletProps
					.get("client.connector.service.url");

			PatientDemographics pd = PatientDemographics.Factory.newInstance();
			PatientId[] idArray = new PatientId[identifiers.size()];
			for (int i = 0; i < identifiers.size(); i++) {
				PatientId id = PatientId.Factory.newInstance();
				id.setRoot(identifiers.get(i).getDomain());
				id.setExtension(identifiers.get(i).getUserValue());
				idArray[i] = id;
			}
			
			for (int i = 0; i < demographics.size(); i++) {
				Demographics dem = demographics.get(i);
				if (dem.getKey().equals("patient.data.surname")) {
					pd.setFamilyName(dem.getUserValue());
				} else if (dem.getKey().equals("patient.data.givenname")) {
					pd.setGivenName(dem.getUserValue());
				} else if (dem.getKey().equals("patient.data.birth.date")) {
					try {
						DateFormat formatter;
						Date date;
						formatter = new SimpleDateFormat("dd/MM/yyyy");
						date = (Date) formatter.parse(dem.getUserValue());
						Calendar cal = Calendar.getInstance();
						cal.setTime(date);
						pd.setBirthDate(cal);
						
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else if (dem.getKey().equals("patient.data.street.address")) {
					pd.setStreetAddress(dem.getUserValue());
				} else if (dem.getKey().equals("patient.data.code")) {
					pd.setPostalCode(dem.getUserValue());
				} else if (dem.getKey().equals("patient.data.city")) {
					pd.setCity(dem.getUserValue());
				} else if (dem.getKey().equals("patient.data.sex")) {
					
				}
			}

			pd.setPatientIdArray(idArray);
			
			ClientConnectorConsumer proxy = new ClientConnectorConsumer(
					serviceUrl);
			log.info("Test Assertions: "
					+ com.liferay.util.portlet.PortletProps
							.get("create.test.assertions"));
			boolean testAssertion = GetterUtil.getBoolean(
					com.liferay.util.portlet.PortletProps
							.get("create.test.assertions"), true);
			Assertion ass = null;
			if (testAssertion) {
				ass = new HCPIAssertionCreator().createHCPIAssertion();
			} else {
				ass = hcpAssertion;
			}
			log.info("Searching for patients in " + selectedCountry);
			log.info("Assertion id: " + ass.getID());

			List<PatientDemographics> queryPatient = proxy.queryPatient(ass, selectedCountry, pd);
			for (PatientDemographics aux : queryPatient) {
				Patient patient = new Patient();
				patient.setName(aux.getGivenName());
				patient.setFamilyName(aux.getFamilyName());
				Calendar cal = aux.getBirthDate();
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
				patient.setBirthDate(sdf.format(cal.getTime()));
				patient.setCity(aux.getCity());
				patient.setAdministrativeGender(aux.getAdministrativeGender());
				patient.setCountry(aux.getCountry());
				patient.setEmail(aux.getEmail());
				patient.setPostalCode(aux.getPostalCode());
				patient.setTelephone(aux.getTelephone());
				patient.setRoot(aux.getPatientIdArray()[0].getRoot());
				patient.setExtension(aux.getPatientIdArray()[0].getExtension());
				patient.setPatientDemographics(aux);
				patients.add(patient);
			}
			TranslationBean tr = new TranslationBean();
			queryPatientsException = tr.getPatient_list_no_patient();
			log.info("Found " + patients.size() + " patients");
			showPatientList = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			patients = new ArrayList<Patient>();
			showPatientList = true;
			TranslationBean tr = new TranslationBean();
			queryPatientsException = tr.getMessage_error() + "\n"
					+ ex.getMessage();
		}
	}

	public void setPatients(List<Patient> patients) {
		this.patients = patients;
	}

	public List<PatientDocument> getPatientDocuments() {

		return patientDocuments;
	}

	public void setPatientDocuments(List<PatientDocument> patientDocuments) {
		this.patientDocuments = patientDocuments;

	}

	public Patient getSelectedPatient() {
		return selectedPatient;
	}

	public void setSelectedPatient(Patient selectedPatient) {
		this.selectedPatient = selectedPatient;
		LiferayUtils.storeToSession("patient", selectedPatient);
	}

	public PatientDocument getSelectedDocument() {
		return selectedDocument;
	}

	public void setSelectedDocument(PatientDocument selectedDocument) {
		this.selectedDocument = selectedDocument;

	}

	// public String getDocumentHtml() {
	// try {
	//
	// selectedEpsosDocument = new EpsosDocument();
	// String serviceUrl = com.liferay.util.portlet.PortletProps
	// .get("client.connector.service.url");
	// ClientConnectorConsumer clientConectorConsumer = new
	// ClientConnectorConsumer(
	// serviceUrl);
	//
	//
	//
	// DocumentId documentId = DocumentId.Factory.newInstance();
	// documentId.setDocumentUniqueId(this.selectedDocument.getUuid());
	// documentId.setRepositoryUniqueId(this.selectedDocument
	// .getRepositoryId());
	// String hcid = this.selectedDocument.getHcid();
	//
	// GenericDocumentCode classCode = GenericDocumentCode.Factory
	// .newInstance();
	// classCode
	// .setNodeRepresentation(PortletProps.get("patient.summary.classCode"));
	// classCode.setSchema(PortletProps.get("classcode.schema"));
	// classCode.setValue(PortletProps.get("patient.summary.value")); // Patient
	// // Summary
	// // ClassCode.
	// EpsosDocument1 eps = clientConectorConsumer.retrieveDocument(
	// hcpAssertion, trcAssertion, selectedCountry, documentId,
	// hcid,classCode);
	// selectedEpsosDocument.setAuthor(eps.getAuthor());
	// selectedEpsosDocument.setCreationDate(eps.getCreationDate());
	// selectedEpsosDocument.setDescription(eps.getDescription());
	// selectedEpsosDocument.setTitle(eps.getTitle());
	//
	// String xmlfile = new String(eps.getBase64Binary(), "UTF-8");
	// EpsosXSLTransformer xlsClass = new EpsosXSLTransformer();
	// String lang1 = LiferayUtils.getPortalLanguage().replace("_", "-");
	// String actionURL = "someurl";
	// documentHtml = xlsClass.transform(xmlfile, lang1, actionURL);
	// System.out.println(documentHtml);
	//
	// } catch (Exception ex) {
	// // ex.printStackTrace();
	// }
	// return documentHtml;
	// }

	public void setDocumentHtml(String documentHtml) {
		this.documentHtml = documentHtml;
	}

	public List<PatientDocument> getPatientPrescriptions() {

		return patientPrescriptions;
	}

	public void setPatientPrescriptions(
			List<PatientDocument> patientPrescriptions) {
		this.patientPrescriptions = patientPrescriptions;
	}

	public boolean getDisablePatientDocuments() {
		User user = LiferayUtils.getPortalUser();

		boolean isPhysician = LiferayUtils.isDoctor(user.getUserId(),
				user.getCompanyId());
		boolean isPharmacist = LiferayUtils.isPharmacist(user.getUserId(),
				user.getCompanyId());
		boolean isNurse = LiferayUtils.isNurse(user.getUserId(),
				user.getCompanyId());
		boolean isAdministrator = LiferayUtils.isAdministrator(
				user.getUserId(), user.getCompanyId());

		if (isNurse)
			return false;
		else if (isPhysician)
			return false;
		else if (isPharmacist)
			return true;
		else if (isAdministrator)
			return false;
		else
			return false;
	}

	public boolean getDisablePrescriptionDocuments() {
		User user = LiferayUtils.getPortalUser();

		boolean isPhysician = LiferayUtils.isDoctor(user.getUserId(),
				user.getCompanyId());
		boolean isPharmacist = LiferayUtils.isPharmacist(user.getUserId(),
				user.getCompanyId());
		boolean isNurse = LiferayUtils.isNurse(user.getUserId(),
				user.getCompanyId());
		boolean isAdministrator = LiferayUtils.isAdministrator(
				user.getUserId(), user.getCompanyId());

		if (isNurse)
			return true;
		else if (isPhysician)
			return false;
		else if (isPharmacist)
			return false;
		else if (isAdministrator)
			return false;
		else
			return false;
	}

	// public String getPrescriptionHtml() {
	//
	// try {
	//
	// selectedEpsosDocument = new EpsosDocument();
	// String serviceUrl = com.liferay.util.portlet.PortletProps
	// .get("client.connector.service.url");
	// ClientConnectorConsumer clientConectorConsumer = new
	// ClientConnectorConsumer(
	// serviceUrl);
	//
	//
	// DocumentId documentId = DocumentId.Factory.newInstance();
	// documentId.setDocumentUniqueId(this.selectedDocument.getUuid());
	// documentId.setRepositoryUniqueId(this.selectedDocument
	// .getRepositoryId());
	// String hcid = this.selectedDocument.getHcid();
	//
	// GenericDocumentCode classCode = GenericDocumentCode.Factory
	// .newInstance();
	// classCode
	// .setNodeRepresentation(PortletProps.get("prescription.classCode"));
	// classCode.setSchema(PortletProps.get("classcode.schema"));
	// classCode.setValue(PortletProps.get("prescription.value"));
	//
	// EpsosDocument1 eps = clientConectorConsumer.retrieveDocument(
	// hcpAssertion, trcAssertion, selectedCountry, documentId,
	// hcid,classCode);
	// selectedEpsosDocument.setAuthor(eps.getAuthor()+"");
	// selectedEpsosDocument.setCreationDate(eps.getCreationDate());
	// selectedEpsosDocument.setDescription(eps.getDescription());
	// selectedEpsosDocument.setTitle(eps.getTitle());
	//
	// String xmlfile = new String(eps.getBase64Binary(), "UTF-8");
	// EpsosXSLTransformer xlsClass = new EpsosXSLTransformer();
	// String lang1 = LiferayUtils.getPortalLanguage().replace("_", "-");
	// String actionURL = "someurl";
	// prescriptionHtml = xlsClass.transform(xmlfile, lang1, actionURL);
	//
	// } catch (Exception ex) {
	// ex.printStackTrace();
	// }
	//
	// return prescriptionHtml;
	// }

	public void setPrescriptionHtml(String prescriptionHtml) {
		this.prescriptionHtml = prescriptionHtml;
	}

	public boolean isShowDemographics() {
		return showDemographics;
	}

	public void setShowDemographics(boolean showDemographics) {
		this.showDemographics = showDemographics;
	}

	public boolean getShowPatientList() {
		return showPatientList;
	}

	public void setShowPatientList(boolean showPatientList) {
		this.showPatientList = showPatientList;
	}

	public StreamedContent getPrescriptionFile() {
		return prescriptionFile;
	}

	public void setPrescriptionFile(StreamedContent prescriptionFile) {
		this.prescriptionFile = prescriptionFile;
	}

	public PatientDocument getSelectedPrescriptionFile() {
		return selectedPrescriptionFile;
	}

	// public void setSelectedPrescriptionFile(
	// PatientDocument selectedPrescriptionFile) {
	// this.selectedPrescriptionFile = selectedPrescriptionFile;
	//
	// try {
	// String serviceUrl = com.liferay.util.portlet.PortletProps
	// .get("client.connector.service.url");
	// ClientConnectorConsumer clientConectorConsumer = new
	// ClientConnectorConsumer(
	// serviceUrl);
	// DocumentId documentId = DocumentId.Factory.newInstance();
	// documentId.setDocumentUniqueId(this.selectedPrescriptionFile
	// .getUuid());
	// documentId.setRepositoryUniqueId(this.selectedPrescriptionFile
	// .getRepositoryId());
	// String hcid = this.selectedPrescriptionFile.getHcid();
	//
	// GenericDocumentCode classCode = GenericDocumentCode.Factory
	// .newInstance();
	// classCode
	// .setNodeRepresentation(PortletProps.get("prescription.classCode"));
	// classCode.setSchema(PortletProps.get("classcode.schema"));
	// classCode.setValue(PortletProps.get("prescription.value"));
	//
	// EpsosDocument1 eps = clientConectorConsumer.retrieveDocument(
	// hcpAssertion, trcAssertion, selectedCountry, documentId,
	// hcid,classCode);
	// selectedEpsosDocument.setAuthor(eps.getAuthor()+"");
	// selectedEpsosDocument.setCreationDate(eps.getCreationDate());
	// selectedEpsosDocument.setDescription(eps.getDescription());
	// selectedEpsosDocument.setTitle(eps.getTitle());
	// prescriptionFile = new DefaultStreamedContent(
	// new ByteArrayInputStream(eps.getBase64Binary()));
	// } catch (Exception ex) {
	// ex.printStackTrace();
	// }
	// }

	public List<Identifier> getIdentifiers() {
		return identifiers;
	}

	public void setIdentifiers(List<Identifier> identifiers) {
		this.identifiers = identifiers;
	}

	public void setCountries(List<Country> countries) {
		this.countries = countries;
	}

	public List<Patient> getPatients() {

		return patients;
	}

	public List<Demographics> getDemographics() {
		return demographics;
	}

	public void setDemographics(List<Demographics> demographics) {
		this.demographics = demographics;
	}

	public boolean isTrcAssertionExists() {
		return trcAssertionExists;
	}

	public void setTrcAssertionExists(boolean trcAssertionExists) {
		this.trcAssertionExists = trcAssertionExists;
	}

	public boolean isTrcAssertionNotExists() {
		return trcAssertionNotExists;
	}

	public void setTrcAssertionNotExists(boolean trcAssertionNotExists) {
		this.trcAssertionNotExists = trcAssertionNotExists;
	}

	public Assertion getHcpAssertion() {
		return hcpAssertion;
	}

	public void setHcpAssertion(Assertion hcpAssertion) {
		this.hcpAssertion = hcpAssertion;
	}

	public Assertion getTrcAssertion() {
		return trcAssertion;
	}

	public void setTrcAssertion(Assertion trcAssertion) {
		this.trcAssertion = trcAssertion;
	}

	public String getPurposeOfUse() {

		return purposeOfUse;
	}

	public void setPurposeOfUse(String purposeOfUse) {
		log.info("TRCA: Starting setting the purpose of use");
		this.purposeOfUse = purposeOfUse;
		PatientId patientId = null;
		try {
			patientId = PatientId.Factory.newInstance();
			patientId.setExtension(selectedPatient.getExtension());
			patientId.setRoot(selectedPatient.getRoot());
			log.info("TRCA: Creating trca for hcpAssertion : " + hcpAssertion.getID() + " for patient " + patientId + ". Purpose of use is : " + purposeOfUse);
			trcAssertion = EpsosHelperService.createPatientConfirmationPlain(
					purposeOfUse, hcpAssertion, patientId);
			log.info("TRCA: Created " + trcAssertion.getID() + " for : " + hcpAssertion.getID() + " for patient " + patientId + ". Purpose of use is : " + purposeOfUse);
			trcAssertionExists = true;
			trcAssertionNotExists = false;

		} catch (PortalException e) {
			log.info("TRCA: Error creating trca for patient : " + patientId.getExtension() + " with hcpAssetion : " + hcpAssertion.getID() + " - " + e.getMessage());
			e.printStackTrace();
			trcAssertionExists = false;
			trcAssertionNotExists = true;

			TranslationBean tr = new TranslationBean();
			queryDocumentsException = tr.getMessage_error() + "\n"
					+ e.getMessage();
		} catch (SystemException e) {
			e.printStackTrace();
			log.info("TRCA: Error creating trca for patient : " + patientId.getExtension() + " with hcpAssetion : " + hcpAssertion.getID() + " - " + e.getMessage());
			trcAssertionExists = false;
			trcAssertionNotExists = false;
			TranslationBean tr = new TranslationBean();
			queryDocumentsException = tr.getMessage_error() + "\n"
					+ e.getMessage();
		}

		// get patient documents

		try {
			patientDocuments = new ArrayList<PatientDocument>();
			String serviceUrl = com.liferay.util.portlet.PortletProps
					.get("client.connector.service.url");
			log.info("CLIENTCONNECTOR: " + serviceUrl);
			ClientConnectorConsumer clientConectorConsumer = new ClientConnectorConsumer(
					serviceUrl);

			patientId = PatientId.Factory.newInstance();
			patientId.setExtension(selectedPatient.getExtension());
			patientId.setRoot(selectedPatient.getRoot());
			GenericDocumentCode classCode = GenericDocumentCode.Factory
					.newInstance();
			classCode.setNodeRepresentation(PortletProps
					.get("patient.summary.classCode"));
			classCode.setSchema(PortletProps.get("classcode.schema"));
			classCode.setValue(PortletProps.get("patient.summary.value")); // Patient
																			// Summary
																			// ClassCode.

			log.info("PS QUERY: Getting ps documents for : " + patientId.getExtension() + " from " + selectedCountry);
			List<EpsosDocument1> queryDocuments = clientConectorConsumer
					.queryDocuments(hcpAssertion, trcAssertion,
							selectedCountry, patientId, classCode);
			log.info("PS QUERY: Found " + queryDocuments.size()  + " for : " + patientId.getExtension() + " from " + selectedCountry);
			for (EpsosDocument1 aux : queryDocuments) {
				PatientDocument document = new PatientDocument();
				document.setAuthor(aux.getAuthor());
				Calendar cal = aux.getCreationDate();
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
				//document.setCreationDate(sdf.format(cal.getTime()));
				document.setDescription(aux.getDescription());
				document.setHealthcareFacility("");
				document.setTitle(aux.getTitle());
				document.setFile(aux.getBase64Binary());
				document.setUuid(aux.getUuid());
				document.setFormatCode(aux.getFormatCode());
				document.setRepositoryId(aux.getRepositoryId());
				document.setHcid(aux.getHcid());
				patientDocuments.add(document);
			}
			TranslationBean tr = new TranslationBean();
			queryDocumentsException = tr.getReport_list_no_document();
		} catch (Exception ex) {
			log.error("PS QUERY: Error getting ps documents for : " + patientId.getExtension() + " from " + selectedCountry + " - " + ex.getMessage());
			ex.printStackTrace();
			TranslationBean tr = new TranslationBean();
			queryDocumentsException = tr.getMessage_error() + "\n"
					+ ex.getMessage();
		}

	}

	public String getPurposeOfUseForPS() {
		return purposeOfUseForPS;
	}

	public void setPurposeOfUseForPS(String purposeOfUseForPS) {
		this.purposeOfUseForPS = purposeOfUseForPS;
		PatientId patientId = null;
		try {
			patientId = PatientId.Factory.newInstance();
			patientId.setExtension(selectedPatient.getExtension());
			patientId.setRoot(selectedPatient.getRoot());
			log.info("TRCA: Creating trca for hcpAssertion : " + hcpAssertion.getID() + " for patient " + patientId + ". Purpose of use is : " + purposeOfUse);
			trcAssertion = EpsosHelperService.createPatientConfirmationPlain(
					purposeOfUseForPS, hcpAssertion, patientId);
			log.debug("TRCA: Created " + trcAssertion.getID() + " for : " + hcpAssertion.getID() + " for patient " + patientId + ". Purpose of use is : " + purposeOfUse);			
			trcAssertionExists = true;
			trcAssertionNotExists = false;

		} catch (PortalException e) {
			log.info("TRCA: Error creating trca for patient : " + patientId.getExtension() + " with hcpAssetion : " + hcpAssertion.getID() + " - " + e.getMessage());
			e.printStackTrace();
			trcAssertionExists = false;
			trcAssertionNotExists = true;

			TranslationBean tr = new TranslationBean();
			queryPrescriptionsException = tr.getMessage_error() + "\n"
					+ e.getMessage();
		} catch (SystemException e) {
			e.printStackTrace();
			log.info("TRCA: Error creating trca for patient : " + patientId.getExtension() + " with hcpAssetion : " + hcpAssertion.getID() + " - " + e.getMessage());
			trcAssertionExists = false;
			trcAssertionNotExists = false;
			TranslationBean tr = new TranslationBean();
			queryPrescriptionsException = tr.getMessage_error() + "\n"
					+ e.getMessage();
		}

		// get prescriptions

		try {
			patientPrescriptions = new ArrayList<PatientDocument>();
			String serviceUrl = com.liferay.util.portlet.PortletProps
					.get("client.connector.service.url");
			ClientConnectorConsumer clientConectorConsumer = new ClientConnectorConsumer(
					serviceUrl);

			patientId = PatientId.Factory.newInstance();
			patientId.setExtension(selectedPatient.getExtension());
			patientId.setRoot(selectedPatient.getRoot());

			GenericDocumentCode classCode = GenericDocumentCode.Factory
					.newInstance();
			classCode.setNodeRepresentation(PortletProps
					.get("prescription.classCode"));
			classCode.setSchema(PortletProps.get("classcode.schema"));
			classCode.setValue(PortletProps.get("prescription.value")); // EP
																		// ClassCode.
			
			log.info("EP QUERY: Getting ep documents for : " + patientId.getExtension() + " from " + selectedCountry);
			List<EpsosDocument1> queryDocuments = clientConectorConsumer
					.queryDocuments(hcpAssertion, trcAssertion,
							selectedCountry, patientId, classCode);
			log.info("PS QUERY: Found " + queryDocuments.size()  + " for : " + patientId.getExtension() + " from " + selectedCountry);
			for (EpsosDocument1 aux : queryDocuments) {
				PatientDocument document = new PatientDocument();
				document.setAuthor(aux.getAuthor());
				Calendar cal = aux.getCreationDate();
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
				document.setCreationDate(sdf.format(cal.getTime()));
				document.setDescription(aux.getDescription());
				document.setHealthcareFacility("");
				document.setTitle(aux.getTitle());
				document.setFile(aux.getBase64Binary());
				document.setUuid(aux.getUuid());
				document.setFormatCode(aux.getFormatCode());
				document.setRepositoryId(aux.getRepositoryId());
				document.setHcid(aux.getHcid());
				patientPrescriptions.add(document);
			}
			TranslationBean tr = new TranslationBean();
			queryPrescriptionsException = tr.getReport_list_no_document();
			log.info("Documents are " + queryDocuments.size());
		} catch (Exception ex) {
			log.error("EP QUERY: Error getting ep documents for : " + patientId.getExtension() + " from " + selectedCountry + " - " + ex.getMessage());
			ex.printStackTrace();
			TranslationBean tr = new TranslationBean();
			queryPrescriptionsException = tr.getMessage_error() + "\n"
					+ ex.getMessage();
		}
	}

	public String getQueryPatientsException() {
		return queryPatientsException;
	}

	public void setQueryPatientsException(String queryPatientsException) {
		this.queryPatientsException = queryPatientsException;
	}

	public String getErrorUserAssertion() {
		return errorUserAssertion;
	}

	public void setErrorUserAssertion(String errorUserAssertion) {
		this.errorUserAssertion = errorUserAssertion;
	}

	public String getQueryDocumentsException() {
		return queryDocumentsException;
	}

	public void setQueryDocumentsException(String queryDocumentsException) {
		this.queryDocumentsException = queryDocumentsException;
	}

	public String getQueryPrescriptionsException() {
		return queryPrescriptionsException;
	}

	public void setQueryPrescriptionsException(
			String queryPrescriptionsException) {
		this.queryPrescriptionsException = queryPrescriptionsException;
	}

}
